package com.bwc.codevideo.speak

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bwc.codevideo.CozeApi
import com.bwc.codevideo.CozeRequest
import com.bwc.codevideo.R
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class SpeakActivity : AppCompatActivity() {
    private var recycler : RecyclerView ?= null
    private var et_inputs : EditText ?= null
    private var btn_send : Button ?= null

    private lateinit var speedAdapter: SpeakAdapter

    private var zongshuru : String ?= null
    private var  shuru : String ?= null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_speak)
        recycler = findViewById(R.id.recycler)
        et_inputs = findViewById(R.id.et_inputs)
        btn_send = findViewById(R.id.btn_send)

        speedAdapter = SpeakAdapter(mutableListOf())
        recycler?.adapter = speedAdapter
        recycler?.layoutManager = LinearLayoutManager(this)
        speedAdapter.addItem("您好，我是您的ai助手，请问您有什么跑步目标吗？我会根据您的目标生成合适的语音提醒哦")

        et_inputs?.addTextChangedListener { text ->
            shuru = text.toString()
        }
        sendAi()
    }

    private fun sendAi() {

        btn_send?.setOnClickListener {
            if (shuru != null){
                speedAdapter.addItem(shuru!!)
                Log.d("SpeakActivity", "sendAi: ${speedAdapter.getUserInput()}")
                val logging = HttpLoggingInterceptor().apply {
                    level = HttpLoggingInterceptor.Level.BODY
                }

                val okHttpClient = OkHttpClient.Builder()
                    .addInterceptor(logging)
                    .build()

                val retrofit = Retrofit.Builder()
                    .baseUrl("https://api.coze.cn/v1/")
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()

                val cozeApi = retrofit.create(CozeApi::class.java)
                val parameters = buildParametersSkippingNulls{
                    this["input"] = speedAdapter.getUserInput()
                }

                val request = CozeRequest(
                    workflowId = "7522301967076933641",
                    parameters = parameters
                )
                val call = cozeApi.runWorkflow(request, "Bearer pat_JG7C6fIyVcpyDjgnyo9w29Y8YX3a1NXX9Rc7lHffka1mSkeowPbk48jvGRJOSS2r")
                call.enqueue(object : Callback<ResponseBody> {
                    override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
                        if (response.isSuccessful) {
                            val responseBody = response.body()?.string()

                            val responseJson = JSONObject(responseBody) // 第一步解析外层 JSON
                            val nestedData = responseJson.getString("data") // 这是嵌套的 JSON 字符串
                            val innerJson = JSONObject(nestedData) // 第二步解析内层 JSON
                            val result = innerJson.getString("data") // 最终拿到你要的内容
                            Log.d("TargetActivity---", result)
                            speedAdapter.addItem(result)
                            shuru = null
                            et_inputs?.text = null
                            Log.d("TargetActivity---", "成功: $responseBody")
                        } else {
                            Log.e("TargetActivity---", "错误码: ${response.code()}")
                        }
                    }

                    override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                        Log.e("TargetActivity---", "网络失败: ${t.message}")
                    }
                })

            }else{
                Toast.makeText(this,"当前数据不能为空", Toast.LENGTH_SHORT).show()
            }
        }

    }
    private fun buildParametersSkippingNulls(
        block: MutableMap<String, Any?>.() -> Unit
    ): Map<String, Any> {
        val tempMap = mutableMapOf<String, Any?>()
        tempMap.block()
        return tempMap.filterValues { it != null } as Map<String, Any>
    }

}